package ru.jexp.rcp.supply;

import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.PartEventAction;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.services.ISourceProviderService;

import ru.jexp.rcp.supply.n.commands.state.JExpSourceProviderStateFactory;
import ru.jexp.rcp.supply.n.commands.state.StateNavigationView;
import ru.jexp.rcp.supply.view.ViewPartNavigation;

public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor
{

	private static final String PERSPECTIVE_ID = "ru.jexp.rcp.supply.perspective";

	public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer)
	{
		return new ApplicationWorkbenchWindowAdvisor(configurer);
	}

	@Override
	public void postStartup()
	{
		IWorkbenchWindow workbenchWindow = getWorkbenchConfigurer().getWorkbench().getActiveWorkbenchWindow();
		workbenchWindow.getActivePage().addPartListener(new InnerPartListener());
	}
	
	public String getInitialWindowPerspectiveId()
	{
		return PERSPECTIVE_ID;
	}

	private class InnerPartListener extends PartEventAction
	{
		protected InnerPartListener()
		{
			super(null);
		}

		@Override
		public void partActivated(IWorkbenchPart part)
		{
			super.partActivated(part);
			if (part instanceof ViewPartNavigation)
			{
				setEnableState(part, false);
			}
		}

		@Override
		public void partClosed(IWorkbenchPart part)
		{
			super.partClosed(part);
			if (part instanceof ViewPartNavigation)
			{
				setEnableState(part, true);
			}
		}

		private void setEnableState(IWorkbenchPart part, boolean enabled)
		{
			ISourceProviderService service = (ISourceProviderService) part.getSite().getWorkbenchWindow().getService(ISourceProviderService.class);
			JExpSourceProviderStateFactory sourceProvider = (JExpSourceProviderStateFactory) service.getSourceProvider(JExpSourceProviderStateFactory.ID);
			StateNavigationView state = (StateNavigationView) sourceProvider.getState(StateNavigationView.ID);
			state.setEnabled(enabled);
		}
	}
}
